package org.jiuling.aliyun.oss;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import org.jiuling.aliyun.config.AliYunConfig;
import org.jiuling.aliyun.oss.config.AliYunOssConfig;

import java.io.*;

/**
 * 阿里云对象存储
 * @author 紫灵
 * @date 2022年10月09日 16时03分54秒
 */
public class AliYunOss {

    /** 阿里云OSS配置 */
    private final AliYunOssConfig aliYunOssConfig;

    public AliYunOss(AliYunOssConfig aliYunOssConfig) {
        this.aliYunOssConfig = aliYunOssConfig;
    }

    /**
     * 上传字符串
     * @param objectName 对象名车给
     * @param str 字符串
     */
    public void uploudString(String objectName,String str){
        // 创建PutObjectRequest对象。
        PutObjectRequest putObjectRequest = new PutObjectRequest(aliYunOssConfig.getBucketName(), objectName,new ByteArrayInputStream(str.getBytes()));
        uploud(putObjectRequest);
    }

    /**
     * 上产流
     * @param objectName 对象名称
     * @param inputStream 输入流
     */
    public void uploudInputStream(String objectName, InputStream inputStream){
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(aliYunOssConfig.getEndpoint(), aliYunOssConfig.getAliYunConfig().getAccessKeyId(), aliYunOssConfig.getAliYunConfig().getAccessKeySecret());
        // 上传对象
        ossClient.putObject(aliYunOssConfig.getBucketName(), objectName,inputStream);
        // 关闭客户端
        ossClient.shutdown();
    }

    /**
     * 上传
     * @param putObjectRequest 上传对象请求
     */
    private void uploud(PutObjectRequest putObjectRequest){
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(aliYunOssConfig.getEndpoint(), aliYunOssConfig.getAliYunConfig().getAccessKeyId(), aliYunOssConfig.getAliYunConfig().getAccessKeySecret());
        // 上传对象
        ossClient.putObject(putObjectRequest);
        // 关闭客户端
        ossClient.shutdown();
    }

    public static void main(String[] args) throws FileNotFoundException {
        AliYunConfig aliYunConfig = new AliYunConfig();
        aliYunConfig.setAccessKeyId("LTAI5tBH1zbBYcbUmMc28vnH");
        aliYunConfig.setAccessKeySecret("k6jn2TTVxrjlFXGefK3dKzLhhbxAn1");

        AliYunOssConfig aliYunOssConfig = new AliYunOssConfig();
        aliYunOssConfig.setAliYunConfig(aliYunConfig);
        aliYunOssConfig.setEndpoint("https://oss-cn-hangzhou.aliyuncs.com");
        aliYunOssConfig.setBucketName("stkj-resource-file");

        File file = new File("C:/Users/STKJ-LYM/Pictures/0-0-0-0100-00221223-2022-12-29-09-37-32.jpg");

        AliYunOss aliYunOss = new AliYunOss(aliYunOssConfig);
        aliYunOss.uploudInputStream("test.jpg",new FileInputStream(file));
    }
}
